<?php
$test = $_POST["json"];
$test = str_replace("[","",$test);
$test = str_replace("]","",$test);
$test = stripslashes($test);
$id_array = split(",",$test);
$i = 0;
foreach ($id_array as $element) {
		$obj = json_decode($element);
		$element_array = split(";",$obj->{''.$i.''});
		$msgid = $element_array[0];
		$delivery_account_id = $element_array[1];
		$delivery_time = $element_array[2];
		$delivery_lat = $element_array[3];
		$delivery_long = $element_array[4];
		$delivery_alt = $element_array[5];
		var_dump($obj);
		var_dump($element_array);
		var_dump($msgid);
		
		if (!@mysql_connect('localhost', 'vidalelu_epic', 'vidale509123')) { error(1); }
		if (!mysql_select_db('vidalelu_epic')) { error(2); }
		if(get_magic_quotes_gpc()) {
		        	$username = stripslashes($_POST['username']);
		    	}
		else{
                	$username = $_POST['username'];
			}
		$bool = ispresent($username,$msgid);
		if($bool){
			echo 1;		

		}else{
			echo 0;
			insert($username,$msgid,$delivery_account_id, $delivery_time, $delivery_lat, $delivery_long, $delivery_alt);
		}
		$i = $i+1;
	}

function ispresent($username,$msgid) {
            $select = "SELECT msgid FROM ". $username ." ";
            $where = "WHERE msgid = '%s'";
            $fixedmsgid = mysql_real_escape_string($msgid);
            $query = sprintf($select.$where, $fixedmsgid);
            $result = mysql_query($query);
            if(mysql_num_rows($result) != 1) { return false; }
            return true;
        }
function error($ec) {
        	printf('error',$ec);
        	die();
        }
function insert($username, $msgid, $delivery_account_id, $delivery_time, $delivery_lat, $delivery_long, $delivery_alt) {
        		
        	$fixedmsgid = mysql_real_escape_string($msgid);
        	$fixeddelivery_account_id  = mysql_real_escape_string($delivery_account_id);
        	$fixeddelivery_long= mysql_real_escape_string($delivery_long);
        	$fixeddelivery_time = mysql_real_escape_string($delivery_time);
        	$fixeddelivery_lat = mysql_real_escape_string($delivery_lat);
        	$fixeddelivery_alt = mysql_real_escape_string($delivery_alt);
        	$insert = "INSERT INTO ".$username." (msgid, delivery_account_id, delivery_time, delivery_lat, delivery_long, delivery_alt) VALUES ('%s','%s','%s','%s','%s','%s')";
        	$query = sprintf($insert, $fixedmsgid, $fixeddelivery_account_id, $fixeddelivery_time, $fixeddelivery_lat, $fixeddelivery_long, $fixeddelivery_alt);
        	var_dump($query);
        	$result = mysql_query($query);
        	return $result;
		}
?>
